package br.consultorio.digital.control;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import br.consultorio.digital.R;
import br.consultorio.digital.modelo.ModelAgendaData;

public class AgendaDataListar extends ListActivity implements TextWatcher {
	protected static final int VOLTAR = 1, AgendaMenu = 2,
			AgendaDataListar = 3;
	private EditText edtagendadata;

	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.agendadata);

		edtagendadata = (EditText) findViewById(R.idAgendaData.edtAgendaData);
		edtagendadata.addTextChangedListener(this);

		buscaTodosAgendaData();
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		Intent it = new Intent();
		it.putExtra("tx_data", (l.getAdapter().getItem(position)).toString());
		setResult(AgendaDataListar, it);
		finish();
	}

	public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
		switch (v.getId()) {
		case R.idAgendaData.edtAgendaData:
			if (!edtagendadata.getText().toString().equals("")
					&& edtagendadata.getText().length() == 10) {
				buscarAgendaData(edtagendadata.getText().toString());
			} else if (edtagendadata.getText().length() > 10) {
				edtagendadata.setText(edtagendadata.getText()
						.subSequence(0, 10));
				buscarAgendaData(edtagendadata.getText().toString());
			} else {
				buscaTodosAgendaData();
			}
			break;
		}
		return false;
	}

	private void buscarAgendaData(String text) {
		ModelAgendaData aModel = new ModelAgendaData(this);
		aModel.tratarConsultaData(edtagendadata.getText().toString());
	}

	private void buscaTodosAgendaData() {
		ModelAgendaData adModel = new ModelAgendaData(this);
		adModel.tratarConsultaTodos();
	}

	public void afterTextChanged(Editable s) {
	}

	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
	}

	public void onTextChanged(CharSequence s, int start, int before, int count) {
		if (start + count == 10) {
			buscarAgendaData(edtagendadata.getText().toString());
		} else if (start + count > 10) {
			edtagendadata.setText(edtagendadata.getText().subSequence(0,
					10));
		} else {
			buscaTodosAgendaData();
		}
	}
}
